require 'java'
require 'rake'
require 'jrake'

class ReloadHandler < org.mortbay.jetty.Handler

  # todo: Should extend AbstractHandler
  #   (need JRuby to support extending abstract classes)
  
  def initialize(rakefile, target, classpath, classname)
    super()
    
    @rakefile = rakefile
    @target = target
    @classpath = classpath
    @classname = classname
  end

  def handle(target,request,response,dispatch)    
    begin
      # Compile any out of date files
      Rake.application.clear
      load @rakefile
      target = Rake.application.lookup(@target)
      raise "Target not found: #{@target}" if target.nil?
      target.invoke
  
      # Load the servlet class, create an instance, and delegate to it
      servlet_class = load_class(@classpath, @classname)      
      servlet = servlet_class.new_instance      
      param_types = to_java_array(java.lang.Class, [
          javax.servlet.ServletRequest,
          javax.servlet.ServletResponse
      ])
      method = servlet_class.get_method("service", param_types)
      args = to_java_array(java.lang.Object, [request,response])
    	method.invoke(servlet, args)      
  	
    rescue Exception => e
        trace = "#{e.class}: #{e.message}<br/>#{e.backtrace.join('<br/>')}"
        response.writer.write("
          <html>
            <body>
              <pre>{trace}</pre>
            </body>
          </html>
        ")
    end
    
    request.handled = true    
  end
  
  def start
  end
  
  def stop
  end
  
  def setServer(server)
    @server = server
  end
  
  def getServer
    @server
  end
end
